package com.zy.controller;

import com.zy.pojo.Role;
import com.zy.pojo.User;
import com.zy.service.PermissionService;
import com.zy.service.RoleService;
import com.zy.vo.ResultVo;
import com.zy.vo.TreeNode;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/sys/role")
public class RoleController {
    @Resource
    private RoleService roleService;
    @Resource
    private PermissionService permissionService;
    @GetMapping("/list")
    public ResultVo getRoleList(){
        return ResultVo.sucess(roleService.getRoleList());
    }
//    @GetMapping("/list")
//    public Object getRoleList(){
//        return roleService.getRoleList();
//    }
//添加
//    @PostMapping("/add")
//    public void add(Role role){
//        role.setCreationDate(new Date());
//        role.setCreatedBy(1);
//        roleService.add(role);
//    }
//添加
@PostMapping("/add")
public ResultVo add(@RequestBody Role role, HttpSession session){
    try{
        User user = (User) session.getAttribute("loginuser");
        if(user!=null){
            role.setCreatedBy(user.getId());
        }
        role.setCreationDate(new Date());
        roleService.add(role);
        return ResultVo.sucess("角色添加成功!");
    }catch(Exception e){
        return ResultVo.fail("角色添加失败了",e);//包含了打印错误日志
    }
}
    //删除
    @GetMapping("/del")
    public ResultVo del(String id){
        try{
            roleService.deleteById(Integer.parseInt(id));
            return ResultVo.sucess("角色删除成功!");
        }catch(Exception e){
            return ResultVo.fail("角色删除失败了",e);//包含了打印错误日志
        }
    }
    //更新
    @PostMapping("/update")
    public ResultVo update(@RequestBody Role role, HttpSession session){
        try{
            User user = (User) session.getAttribute("loginuser");
            if(user!=null){
                role.setModifyBy(user.getId());
            }
//            role.setModifyDate(new Date());
            roleService.update(role);
            return ResultVo.sucess("角色修改成功!");
        }catch(Exception e){
            return ResultVo.fail("角色修改失败了",e);//包含了打印错误日志
        }
    }
    @GetMapping("/grant")
    public ResultVo grant(Integer roleId){
        List<TreeNode> list=permissionService.gteTreeNodes(roleId);
        return ResultVo.sucess(list);
    }
    @GetMapping("/dogrant")
    public ResultVo dogrant(Integer roleId,Integer[] nid){
       try{
        permissionService.dogrant(roleId,nid);
        return ResultVo.sucess("角色授权成功");
       }catch (Exception e){
        return ResultVo.fail("角色授权失败",e);
       }
    }
}
